<template>
  <div>
    <!-- 用户列表：点击侧边栏的二级菜单用户列表跳到该组件 -->
    <!-- 面包屑区域导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 输入框与添加 -->
      <el-row :gutter="10">
        <el-col :span="8">
          <!-- query是搜索的关键字  clearable清空输入框内容 clear清空内容之后将数据同步-->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList()">
              <el-button slot="append" icon="el-icon-search" @click="getUsersList()"></el-button>
            </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table
        :data="usersList"
        style="width: 100%"
        border
        stripe>
        <el-table-column
          label="#"
          type='index'>
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop='role_name'
          label='角色'>
        </el-table-column>
        <el-table-column
          prop='mg_state'
          label='状态'>
          <template slot-scope="scope">
            <!-- 通过作用域插槽拿到数据 {{scope.row}}  表示当前这一行的数据-->
            <el-switch
              v-model="scope.row.mg_state" @change="userStatusChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label='操作'>
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size='mini' @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size='mini' @click='deleteById(scope.row.id)'></el-button>
            <!-- 分配角色 提示 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size='mini'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 添加用户的对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="adddialogVisible"
        width="50%" @close='adddialogClosed'>
        <!-- 内容主体区域 -->
        <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="70px">
          <!-- 用户名验证 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <!-- 密码验证 -->
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%" @close='editDialogClosed'>
        <!-- 主体框 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm" >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱和表单验证
    var checkEmail = (rule, value, callbaxk) => {
      var regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (!regEmail.test(value)) {
        return callbaxk(new Error('请填写正确的邮箱格式'))
      }
      callbaxk()
    }
    var checkMobile = (rule, value, callbaxk) => {
      var regMobile = /^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/

      if (!regMobile.test(value)) {
        return callbaxk(new Error('请填写正确的手机号'))
      }
      callbaxk()
    }
    return {
      input: '',
      // 用户列表需要的参数
      queryInfo: {
        // 查询参数
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前条数
        pagesize: 3
      },
      total: 0,
      pagenum: 1,
      // 用户列表
      usersList: [],
      // 控制添加用户的对话框的显示和隐藏
      adddialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      // 添加表单的验证规则对象
      addFormrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 隐藏弹出框
      editDialogVisible: false,
      // 编辑用户表单数据,查询到的用户信息对象
      editForm: {},
      // 编辑表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取用户列表：向后台请求数据
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('用户列表获取失败')
      }
      this.total = res.data.total
      this.pagenum = res.data.pagenum
      this.usersList = res.data.users
      // console.log(this.pagenum)
    },
    // 监听 pagesize 的改变
    handleSizeChange (newSize) {
      // console.log(newSize) 将监听到的值重新渲染
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // 监听 页码的改变
    handleCurrentChange (newPage) {
      // console.log(newSize)
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    // 更改swich的状态，通过el的事件，然后发送请求给后台更改状态
    async userStatusChanged (userinfo) {
      // console.log(userinfo)
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state // 更新失败就将视图的状态值恢复原样
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态更新成功')
    },
    // 监听用户对话框关闭事件
    adddialogClosed () {
      // resetField与视频不一致的原因？？？ 重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 表单在点击确定时预验证
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // 验证成功发起新的请求
        const { data: res } = await this.$http.post('users', this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('用户创建失败')
        }
        this.$message.success('用户创建成功')
        // 成功之后隐藏对话框
        this.adddialogVisible = false
        this.getUsersList()
      })
    },
    // 展示用户编辑对话框
    async showEditDialog (id) {
      this.editDialogVisible = true
      // console.log(id)
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.editForm = res.data
      // console.log(this.editForm)
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed () {
      // resetField与视频不一致的原因？？？ 重置表单
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid) 布尔值
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // 请求 修改用户
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        // 提示修改成功
        this.$message.success('用户创建成功')
        // 成功之后隐藏对话框
        this.editDialogVisible = false
        this.getUsersList()
      })
    },
    // 询问并删除按钮操作(id由来：获取当前行的id 通过插槽solt)
    async deleteById (id) {
      const confirmresult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 点击取消 确定 分别为cancel confirm
      // console.log(confirmresult)
      if (confirmresult !== 'confirm') {
        return this.$message.info('已取消删除用户')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 400) {
        this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUsersList()
    }

  },
  created () {
    this.getUsersList()
  }
}
</script>

<style>

</style>
